package com.sg.service.base.framework.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sg.common.util.CommonFunctionHelper;
import com.sg.dto.base.framework.req.BatchQueryBizObjectNamesListReq;
import com.sg.dto.base.framework.req.QueryBizObjectDetailReq;
import com.sg.dto.base.framework.req.QueryBizObjectListReq;
import com.sg.entity.MetadataBusinessObject;
import com.sg.service.base.framework.MMetadataBusinessObjectService;
import com.wicket.okrframework.common.dto.FieldInfo;
import com.wicket.okrframework.common.exception.BizException;
import com.wicket.okrframework.dal.mapper.mbg.MetadataBusinessObjectMapper;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Tags;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ：
 * @version 1.0
 * @since 2022/1/19 15:39
 */
@Service
public class MMetadataBusinessObjectServiceImpl
        extends ServiceImpl<MetadataBusinessObjectMapper, MetadataBusinessObject>
        implements MMetadataBusinessObjectService {

    @Autowired
    MetadataBusinessObjectMapper metadataBusinessObjectMapper;

    /**
     * 1-1-03批量查询业务对象名称列表（集合公用）[651]
     * gen by moon at 8/31/2022, 7:25:51 PM
     */
    @Trace(operationName = "1-1-03批量查询业务对象名称列表（集合公用）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<MetadataBusinessObject> batchQueryBizObjectNamesList(BatchQueryBizObjectNamesListReq reqDto) {

        try {
            QueryWrapper<MetadataBusinessObject> queryWrapper = new QueryWrapper<>();
            reqDto.setIsValid("FALSE");
            if (reqDto.getBusinessObjectIdList() == null || reqDto.getBusinessObjectIdList().isEmpty()) {
                return new ArrayList<>();
            }
            queryWrapper.in("business_object_id", reqDto.getBusinessObjectIdList());
            Map<String, Object> fieldInfoMap = null;
            fieldInfoMap = CommonFunctionHelper.objectToMapForLamBda(reqDto);
            List<FieldInfo> compareList = CommonFunctionHelper.getRangeField(MetadataBusinessObject.class);
            CommonFunctionHelper.buildQueryWrapperCompare(queryWrapper, compareList, fieldInfoMap);
            List<FieldInfo> likeList = CommonFunctionHelper.getLikeFiled(MetadataBusinessObject.class);
            CommonFunctionHelper.buildQueryWrapperLike(queryWrapper, likeList, fieldInfoMap);
            likeList.addAll(compareList);
            CommonFunctionHelper.buildQueryWrapperEq(queryWrapper, fieldInfoMap, likeList);
            List<FieldInfo> orderList = CommonFunctionHelper.getOrderList(MetadataBusinessObject.class);
            //CommonFunctionHelper.buildQueryWrapperOrder(queryWrapper, orderList);

            return ((List<MetadataBusinessObject>) super.list(queryWrapper));
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("-1", e, false);
        }
    }

    /**
     * 1-1-03查询业务对象列表[219]
     * gen by moon at 8/31/2022, 7:25:50 PM
     */
    @Trace(operationName = "1-1-03查询业务对象列表")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<MetadataBusinessObject> queryBizObjectList(QueryBizObjectListReq reqDto) {

        try {
            QueryWrapper<MetadataBusinessObject> queryWrapper = new QueryWrapper<>();
            reqDto.setIsValid("FALSE");
            reqDto.setSpaceId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecSpaceId());//CURRENT_SPACEID
            reqDto.setAppId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecAppId());//CURRENT_APPID

            Map<String, Object> fieldInfoMap = null;
            fieldInfoMap = CommonFunctionHelper.objectToMapForLamBda(reqDto);
            List<FieldInfo> compareList = CommonFunctionHelper.getRangeField(MetadataBusinessObject.class);
            CommonFunctionHelper.buildQueryWrapperCompare(queryWrapper, compareList, fieldInfoMap);
            List<FieldInfo> likeList = CommonFunctionHelper.getLikeFiled(MetadataBusinessObject.class);
            CommonFunctionHelper.buildQueryWrapperLike(queryWrapper, likeList, fieldInfoMap);
            likeList.addAll(compareList);
            CommonFunctionHelper.buildQueryWrapperEq(queryWrapper, fieldInfoMap, likeList);
            List<FieldInfo> orderList = CommonFunctionHelper.getOrderList(MetadataBusinessObject.class);
            //CommonFunctionHelper.buildQueryWrapperOrder(queryWrapper, orderList);
            queryWrapper.orderByDesc("operate_time");
            return ((List<MetadataBusinessObject>) super.list(queryWrapper));
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("-1", e, false);
        }
    }

    /**
     * 【验证接口】验证集合取第一条数据[2400]
     * gen by moon at 8/31/2022, 7:25:51 PM
     */
    @Trace(operationName = "【验证接口】验证集合取第一条数据")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean validationCollectionFirstData(List<MetadataBusinessObject> metadataBusinessObject) {

        if (metadataBusinessObject == null || metadataBusinessObject.size() == 0) {
            return false;
        }

        return super.saveBatch(metadataBusinessObject.stream().map(item -> {

            return item;
        }).collect(Collectors.toList()));
    }

    /**
     * 1-1-03查询业务对象详情[12]
     * gen by moon at 8/31/2022, 7:25:50 PM
     */
    @Trace(operationName = "1-1-03查询业务对象详情")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public MetadataBusinessObject queryBizObjectDetail(QueryBizObjectDetailReq reqDto) {

        try {
            reqDto.setIsValid("FALSE");
            QueryWrapper<MetadataBusinessObject> queryWrapper = new QueryWrapper<>();
            Map<String, Object> fieldInfoMap = null;
            fieldInfoMap = CommonFunctionHelper.objectToMapForLamBda(reqDto);
            CommonFunctionHelper.buildQueryWrapperEq(queryWrapper, fieldInfoMap, new ArrayList<>());
            queryWrapper.orderByDesc("create_time");
            List<MetadataBusinessObject> retList = super.list(queryWrapper);
            if (retList != null && retList.size() > 0) {
                MetadataBusinessObject retData = retList.get(0);

                return retData;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("-1", e, false);
        }
    }

    /**
     * 1-1-03删除业务对象[11]
     * gen by moon at 8/31/2022, 7:25:49 PM
     */
    @Trace(operationName = "1-1-03删除业务对象")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBizObject(String businessObjectId) {

        return super.removeById(businessObjectId);
    }

    /**
     * 1-1-03修改业务对象	[10]
     * gen by moon at 8/31/2022, 7:25:49 PM
     */
    @Trace(operationName = "1-1-03修改业务对象	")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBizObject(MetadataBusinessObject metadataBusinessObject) {
        metadataBusinessObject.setOperationInductionId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecInductionRecordId());//CURRENT_INDUCTIONID
        metadataBusinessObject.setOperateTime(CommonFunctionHelper.getCurrentTime());//SYSTEM_CURRENT_TIME
        if (metadataBusinessObject != null && metadataBusinessObject.getSubjectLifeCycle() != null && metadataBusinessObject.getSubjectLifeCycle().equals("CURRENTLY_VALID")) {
            metadataBusinessObject.setReleaseInductionId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecInductionRecordId());//RELEASED_CURRENT_INDUCTIONID
        }
        if (metadataBusinessObject != null && metadataBusinessObject.getSubjectLifeCycle() != null && metadataBusinessObject.getSubjectLifeCycle().equals("CURRENTLY_VALID")) {
            metadataBusinessObject.setReleaseTime(CommonFunctionHelper.getCurrentTime());//RELEASE_SYSTEM_CURRENT_TIME
        }
        return super.updateById(metadataBusinessObject);
    }

    /**
     * 1-1-03新增业务对象[9]
     * gen by moon at 8/31/2022, 7:25:48 PM
     */
    @Trace(operationName = "1-1-03新增业务对象")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addBizObject(MetadataBusinessObject metadataBusinessObject) {
        metadataBusinessObject.setBusinessObjectId(CommonFunctionHelper.getUid());//DISTRIBUTED_ID
        metadataBusinessObject.setOperationInductionId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecInductionRecordId());//CURRENT_INDUCTIONID
        metadataBusinessObject.setOperateTime(CommonFunctionHelper.getCurrentTime());//SYSTEM_CURRENT_TIME
        metadataBusinessObject.setIsArchive("FALSE");
        metadataBusinessObject.setCreateInductionId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecInductionRecordId());//CURRENT_INDUCTIONID
        if (metadataBusinessObject != null && metadataBusinessObject.getSubjectLifeCycle() != null && metadataBusinessObject.getSubjectLifeCycle().equals("CURRENTLY_VALID")) {
            metadataBusinessObject.setReleaseInductionId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecInductionRecordId());//RELEASED_CURRENT_INDUCTIONID
        }
        metadataBusinessObject.setCreateTime(CommonFunctionHelper.getCurrentTime());//SYSTEM_CURRENT_TIME
        if (metadataBusinessObject != null && metadataBusinessObject.getSubjectLifeCycle() != null && metadataBusinessObject.getSubjectLifeCycle().equals("CURRENTLY_VALID")) {
            metadataBusinessObject.setReleaseTime(CommonFunctionHelper.getCurrentTime());//RELEASE_SYSTEM_CURRENT_TIME
        }
        metadataBusinessObject.setIsValid("FALSE");
        metadataBusinessObject.setSpaceId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecSpaceId());//CURRENT_SPACEID
        metadataBusinessObject.setAppId(CommonFunctionHelper.getBaseInfoFromLocal().getSpecAppId());//CURRENT_APPID
        if (super.save(metadataBusinessObject)) {
            return metadataBusinessObject.getBusinessObjectId();
        } else {
            return "-1";
        }

    }
}
